from engineio import json
from flask import Blueprint,jsonify,make_response
from db import db
import datetime
import random
import redis
from flask import current_app as app,request
from flask_restful import reqparse
from utils.captcha.captcha import captcha
from utils.myrly import send_message
from utils.myredis import MyRedis, r
from utils.myjwt import MyJwt, myjwt
import time

user_blue = Blueprint('user',__name__)

@user_blue.route("/test")
def test():
    str = datetime.datetime.strftime(datetime.datetime.now(),'%Y-%m-%d %H:%M:%S')+"   "+request.path+"   error"
    app.logger.error(str)
    app.logger.info('info log')
    app.logger.warning('warning log')
    
    sql = "insert into user values(0,'aa22222','abc')"
    db.update(sql)
    db.commit()
    sql1 = "select * from user"
    res = db.find_all(sql1)
    print(res)
    return 'ok234234'



# 发送验证码
@user_blue.route("/sendcode",methods=["POST"])
def sendcode():
    # 获取手机号
    req = reqparse.RequestParser()
    req.add_argument('mobile')
    args = req.parse_args()
    mobile = args['mobile']

    if not all([mobile]):
        return jsonify({
            'code':204,
            'msg':'信息不完整',
        })

    # 2. 生成短信验证码
    smscode = random.randint(100000, 999999)
    # 设置过期时间
    exp = 5
    # 调用封装好的容联云  传参
    res = send_message(mobile, smscode, exp)
    print("res:", res)

    # 将手机号 短信验证码 过期时间存入redis中
    if res:
        rds = redis.Redis(host='localhost', db=6, port=6379)
        rds.set(mobile, smscode, 300)
        return jsonify({'message': '发送成功', 'code': 200, 'smscode': smscode})
    else:
        return jsonify({'msg': '发送失败', 'code': 500})



# 登录
@user_blue.route("/login")
def login():
    req = reqparse.RequestParser()
    req.add_argument('mobile', required=True)
    req.add_argument('code', required=True)
    args = req.parse_args()

    if not all([args['mobile'], args['code']]):
        return jsonify({
            "code": 400,
            "msg": '参数填写完整'
        })
    key = 'sms_%s' % args['mobile']
    rs = MyRedis().get_str(key)
    if not rs:
        return jsonify({
            "code": 400,
            "msg": '验证码过期'
        })
    if rs.decode() != args['code']:
        return jsonify({
            "code": 400,
            "msg": '验证码错误'
        })
    sql = "select * from user where phone='%s'" % args['mobile']
    rs = db.find_all(sql)
    # 没有用户
    if not rs:
        sql = 'insert into user(phone) values (%s,)' % args['mobile']
        db.update(sql)
        db.commit()

    sql = 'select * from user where phone=%s' % args['mobile']
    rs = db.find_all(sql)
    payload = {'data': {
        "id": rs[0]['id'],
        'name': rs[0]['name']
    }}
    token = MyJwt().jwt_encode(payload)
    return jsonify({
        "code": 200,
        "msg": '登录成功',
        "token": token
    })




# 生成图片验证码
@user_blue.route("/create_imagecode")
def create_imagecode():
    name,text,image = captcha.generate_captcha()
    res = make_response(image)
    res.headers['Content-Type'] = "image/jpg"
    # 存入redis
    return res




# 员工管理
@user_blue.route('/empManger',methods=["POST","GET"])
def empManager():
    return 'ok'


@user_blue.route('/get_wb')
def get_weibo():
    client_id = "3674019597"
    redirect_uri = "http://127.0.0.1:8000/user/weiboCallback/"
    url = ""
    return jsonify({
        "url":url
    })








